<!-- 随堂练习-添加习题-填空题 -->
<template>
  <div id="p-practiceAddFillInTheBlanks">
    <div class="courses-nav jx-content">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="习题类型 :">
          <el-select :disabled="disabledQuestionType" v-model="questionTypeMessage" placeholder="请选择" @change="getTopicModel">
            <el-option v-for="(item,index) in questionTypeList" :key="index" :label="item.message" :value="item.type"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <div class="jx-content">
      <div class="answer-editor">
        <h2 class="jx-title">习题题目</h2>
        <mavonEditor ref="question"></mavonEditor>
        <div class="c-red">提示：输入题目时，填空部分用英文括号(+)代替</div>
      </div>
      <div class="question-editor">
        <h2 class="jx-title">习题答案</h2>
        <mavonEditor ref="answer"></mavonEditor>
        <div class="c-red">提示：输入答案时，使用, 分割</div>
      </div>
      <div class="answer-editor">
        <h2 class="jx-title">答案解析</h2>
        <mavonEditor ref="analysis"></mavonEditor>
      </div>
      <div class="btn-group">
        <!-- <button @click="getAnswerHtml" class="button-style">获取问题内容</button> -->
        <button v-if="!rowId" @click="addQuestion" class="button-style question-submit">保 存</button>
        <button v-if="rowId" @click="editQuestion" class="button-style question-submit">保存修改</button>
      </div>
    </div>
  </div>
</template>
<script>
import mavonEditor from "../../../components/mavonEditor";
import axios from "axios";
import $ from "jquery";
export default {
  components: { mavonEditor },
  data() {
    return {
      questionTypeMessage: "填空题",
      disabledQuestionType: false,
      //题目类型数组
      questionTypeList: [],
      //章节数组
      chapterList: [],
      addForm: {
        //章节ID
        chapterId: this.$localstorage.getLocalStorage("chapterInfoData")
          .chapterId,

        //习题类型
        questionType: 3,
        //问题描述，题干
        content: "",
        htmlContent: "",
        //答案解析
        jxContent:"",
        jxContentHtml:"",
        //备选答案
        answer: [
          {
            content: ""
            //isCorrect:true,
          }
        ]
        //查重百分比
        //duplicatePercent:50
      },
      toolbars: {
        bold: false, // 粗体
        italic: false, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: false, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true // 预览
      },
      rowId: "",
      //取searchForm
      itemBankSearchForm: this.$localstorage.getLocalStorage("searchFormP"),
      //取itemBankName
      itemBankName: this.$localstorage.getLocalStorage("itemBankNameP")
    };
  },
  computed: {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getTopicSelected();
      this.getRowData();
    },
    //提交验证
    reQuestion() {
      let that = this;
      let addForm = that.addForm;

      //添加问题
      that.addForm.content = that.$refs["question"].value;
      that.addForm.htmlContent = that.$refs.question.getRender();
      //添加答案解析
      that.addForm.jxContent = that.$refs["analysis"].value;
      that.addForm.jxContentHtml = that.$refs.analysis.getRender();
      if(that.addForm.jxContent == ''){
        that.addForm.jxContentHtml = '';
      }
      if(that.addForm.jxContent && that.addForm.jxContent.length > 10000){
        that.$message.warning("答案解析文字长度不能超过10000字符");
        return false;
      }
      if(that.addForm.jxContentHtml && that.addForm.jxContentHtml.length > 10000){
        that.$message.warning("答案解析文字长度不能超过10000字符");
        return false;
      }

      //把中文括号替换为英文
      that.addForm.content = that.addForm.content.replace(/（/g, "(");
      that.addForm.content = that.addForm.content.replace(/）/g, ")");
      that.addForm.htmlContent = that.addForm.htmlContent.replace(/（/g, "(");
      that.addForm.htmlContent = that.addForm.htmlContent.replace(/）/g, ")");

      //添加答案
      that.addForm.answer[0].content = that.$refs["answer"].value;
      that.addForm.answer[0].htmlContent = that.$refs.answer.getRender();

      if (addForm.content.match(/^\s*$/)) {
        that.$message.warning("请填写题干");
        return false;
      }
      if (addForm.content.search(/\(\+\)/g) === -1) {
        that.$message.warning("至少添加一个空");
        return false;
      }
      if (addForm.answer[0].content.match(/^\s*$/)) {
        that.$message.warning("请填写答案内容");
        return false;
      }
      return true;
    },
    //添加习题
    addQuestion() {
      var that = this;
      //提交前验证
      let isNull = that.reQuestion();
      if (!isNull) {
        return;
      }
      const loading = that.$loading({
        lock: true,
        text: "正在保存中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      axios
        .post(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/2/question-repository/question",
          that.addForm
        )
        .then(function(res) {
          loading.close();
          console.log("成功1");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              that.$message({
                message: "添加成功",
                type: "success"
              });
              that.$router.push({
                name: that.itemBankName,
                params: {
                  searchForm: that.itemBankSearchForm
                }
              });
            } else {
              that.$message({
                message: res.data.message,
                type: "error"
              });
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //通过id获取题目信息
    getRowData() {
      var that = this;
      let rowId = that.$route.query.rowId;
      that.rowId = rowId;
      if (!rowId) {
        return;
      }
      that.disabledQuestionType = true;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/2/question-repository/question/" +
            rowId
        )
        .then(function(res) {
          console.log("成功1");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              that.addForm = res.data.data;
              that.setEditDom();
            } else {
              that.$message({
                message: res.data.message,
                type: "error"
              });
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //回填
    setEditDom() {
      let that = this;
      let addForm = that.addForm;
      that.$refs.question.changeVal(addForm.content);
      that.$refs.answer.changeVal(addForm.answer[0].content);
      that.$refs.analysis.changeVal(addForm.jxContent);
    },
    //修改习题
    editQuestion() {
      var that = this;
      let rowId = that.rowId;
      let isNull = that.reQuestion();
      if (!isNull) {
        return;
      }
      const loading = that.$loading({
        lock: true,
        text: "正在保存中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      axios
        .put(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/2/question-repository/question/" +
            rowId,
          that.addForm
        )
        .then(function(res) {
          loading.close();
          console.log("成功1");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              that.$message({
                message: "修改成功",
                type: "success"
              });
              that.$router.push({
                name: that.itemBankName,
                params: {
                  searchForm: that.itemBankSearchForm
                }
              });
            } else {
              that.$message({
                message: res.data.message,
                type: "error"
              });
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //获取题目类型和章节下拉
    getTopicSelected() {
      var that = this;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/2/question-repository/dropdown-list"
        )
        .then(function(res) {
          console.log("成功");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              console.log(res.message);
              //赋值题目类型
              let questionTypeList = res.data.data.questionTypeList;
              that.questionTypeList = questionTypeList;
              //赋值章节列表
              let chapterList = res.data.data.chapterList;
              that.chapterList = chapterList;
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //获取题目类型
    getTopicModel(val) {
      this.addForm.questionType = val;
      switch (val) {
        case 1:
          this.$router.push({
            path: "PracticeAddChoiceQuestion"
          });
          break;
        case 2:
          this.$router.push({
            path: "PracticeAddJudge"
          });
          break;
        case 3:
          this.$router.push({
            path: "PracticeAddFillInTheBlanks"
          });
          break;
        case 4:
          this.$router.push({
            path: "PracticeAddShortAnswerQuestions"
          });
          break;
        case 7:
          this.$router.push({
            path: "PracticeAddEnclosure"
          });
          break;
        //暂时没有编程和实验
        // case 5:
        //   this.$router.push({
        //     path: "/Teaching/MyCourses/Examination/addJudge"
        //   });
        //   break;
        // case 6:
        //   this.$router.push({
        //     path: "/Teaching/MyCourses/Examination/addExperimental"
        //   });
        //   break;
        default:
          console.log(1234);
      }
    }
  }
};
</script>
<style lang="scss">
@import "./../../../styles/layout/color_variables";

body {
  background: $bg-gray;
}
#p-practiceAddFillInTheBlanks {
  //编辑器设置z-index
  @for $i from 1 through 15 {
    //$item: nth($stars, $i);
    .question-choice {
      &:nth-child(#{$i}) {
        .v-note-wrapper.markdown-body {
          position: relative;
          z-index: 16-$i;
        }
      }
    }
  }
  .fullscreen {
    top: 60px;
    z-index: 99999;
  }
  position: relative;
  z-index: 1;
  width: $width;
  margin: 20px auto;
  color: #727272;
  .el-form-item {
    margin-bottom: 0;
  }
  //保存提交
  .question-submit {
    margin-left: -111px;
  }
  //编辑器
  .v-note-wrapper {
    min-height: 120px;
  }
  .form-group {
  }
  .btn-group {
    text-align: center;
  }
  .answer-editor {
    margin-bottom: 60px;
    .v-note-wrapper {
      min-height: 150px;
    }
  }
  .question-editor {
    .jx-title {
      display: flex;
      justify-content: space-between;
    }
  }
  .question-choice {
    display: flex;
    margin-bottom: 40px;
    .question-left {
      color: #727272;
      min-width: 30px;
    }
    .question-center {
      width: 100%;
    }
    .question-right {
      min-width: 140px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .question-del {
        width: 20px;
        height: 20px;
        padding: 0;
        font-size: 24px;
        border-radius: 20px;
        color: $title-gray;
        border: 1px solid $title-gray;
        text-align: center;
        line-height: 6px;
        cursor: pointer;
        &:hover {
          color: #1277eb;
          border: 1px solid #1277eb;
        }
      }
      .question-del.is-disabled {
        &:hover {
          color: #c0c4cc;
          cursor: not-allowed;
          background-image: none;
          background-color: #fff;
          border-color: #ebeef5;
        }
      }
      .question-label {
        .chose-del {
          color: #727272;
          margin-right: 10px;
          vertical-align: middle;
        }
      }
    }
  }
}
</style>
